<?php

namespace App\Services\Account;

use App\Models\User;
use Brick\Math\BigDecimal;
use Brick\Math\RoundingMode;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Relations\HasMany;

abstract class AccountAbstract
{
    protected User $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    protected function record(BigDecimal $money, $remark, $reason, $data = [])
    {
        DB::transaction(function () use ($money, $remark, $reason, $data) {

            /**
             * @var User $user
             */
            $user = User::find($this->user->id);

            $field = $this->account_field();

            $origin = $user->{$field};
            
            $money = $money->toScale(2, RoundingMode::HALF_UP);

            $userMoneyWillBe = big_decimal($user->{$field})->plus($money);

            $this->account()->create([
                'origin' => $origin,
                'result' => (string)$userMoneyWillBe,
                'money' => (string)$money,
                'remark' => $remark,
                'reason' => $reason,
                'data' => $data,
            ]);

            $user->update([$field => (string)$userMoneyWillBe]);
        });
    }

    abstract protected function account(): HasMany;
}
